//
//  XS_AlertC.swift
//  XS_Base
//
//  Created by 韩云智 on 2020/10/29.
//

import UIKit
import SnapKit
 
public extension UIViewController {
    /// 展示弹框
    open func showAlert(preferredStyle: UIAlertController.Style = .alert,title:String? = nil, message: String? = nil, actions: [AlertActionModel] = [], sourceView: UIView? = nil) {
        let vc = XS_AlertC(title: title, message: message, preferredStyle: preferredStyle)
        
        for model in actions {
            switch model.type {
            case .action:
                let action = UIAlertAction(title: model.title, style: model.style, handler: model.handler)
                vc.addAction(action)
            case .textField:
                vc.addTextField(configurationHandler: model.textField)
            case .custom:
                if let customView = model.view, let closure = model.closure {
                    vc.view.addSubview(customView)
                    customView.snp.makeConstraints(closure)
                }
                if #available(iOS 11, *) {} else {
                    if let view = vc.view.subviews.first!.subviews.first!.subviews.first!.subviews.first {
                        view.snp.makeConstraints { maker in
                            maker.top.left.right.equalToSuperview()
                            maker.bottom.equalToSuperview().offset(-44)
                        }
                    }
                }
            }
        }
        if UIDevice.current.userInterfaceIdiom == .pad {
            let popPresenter = vc.popoverPresentationController
            if let sourceView = sourceView {
                popPresenter?.sourceView = sourceView
                popPresenter?.sourceRect = sourceView.bounds
            }
        }
        present(vc, animated: true, completion: nil)
    }
}

open class AlertActionModel {
    public enum AlertActionModelType {
        case action // 按键
        case textField // 输入框
        case custom // 自定义视图
    }
    open var type: AlertActionModelType = .action
    // action
    open var title: String?
    open var style: UIAlertAction.Style = .default
    open var handler: ((UIAlertAction) -> Void)?
    // textField
    open var textField: ((UITextField) -> Void)? = nil
    // custom
    open var view: UIView? // 自定义视图
    open var closure: ((ConstraintMaker) -> Void)? // 对自定义视图的布局
    public init() {}
}

open class XS_AlertC: UIAlertController {
    deinit {
        xsDebug { print("deinit: \(type(of: self))") }
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        xsDebug { print("load: \(type(of: self))") }
        view.tintColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        if #available(iOS 13.0, *) {
            overrideUserInterfaceStyle = .light
        }
    }
}
